<?php
  date_default_timezone_set('Asia/Kolkata');

  $msg = '';
  session_start();
  $debug = true;
  $debugArr = array();
  $site = 'http://localhost/nb158m/try';
  $linkExpireTime = 60*60; # Seconds
  /******************************
   * DB Connection start
   * ****************************/
  $userName = 'root';
  $password = '';
  $hostName = 'localhost';
  $dbName = 'nb158m';

  mysql_connect($hostName, $userName, $password)
  or die(mysql_error());
  mysql_select_db($dbName)or die(mysql_error());
  /*****************************************/

  function pr($arr)
  {
    $from = debug_backtrace();
    $line = $from[0]['line'];
    $file = $from[0]['file'];


    global $debug;
    global $debugArr;
    if($debug == false) return false;

    $msg =  "$file on Line $line ";

    $msg .=  '<pre style="color:#fff;background-color:#000;padding:10px;font-size:20px;border-radius:10px;box-shadow:10px 10px 10px gray">';
    $msg .= print_r($arr, true);
    $msg .=  '</pre>';
    $debugArr[] = $msg;
  }

  function pr1($arr)
  {

    $msg =  '<pre style="color:#fff;background-color:#000;padding:10px;font-size:20px;border-radius:10px;box-shadow:10px 10px 10px gray">';
    $msg .= print_r($arr, true);
    $msg .=  '</pre>';
    echo $msg;
  }

  function pq($str)
  {
    global $debug;
    global $debugArr;
    if($debug == false) return false;

    $msg = '<div style="color:#ff0000;background-color:yellow;padding:10px;font-size:20px;border-radius:10px;box-shadow:10px 10px 10px gray">';
    $msg .= ($str);
    $msg .= '</div>';
    $debugArr[] = $msg;
  }

  function jsRedirect($path='')
  {
    if($path == '')return false;

    echo '<script type="text/javascript">';
    echo 'window.location="'.$path.'"';
    echo '</script>';
    exit;
  }

  function setFlashMessage($msg='')
  {
    if(!isset($_SESSION['msg'])){
      $_SESSION['msg'] = array();
    }

    array_push($_SESSION['msg'],$msg );
  }

  function getFlashMessage()
  {
    if(!isset($_SESSION['msg'])) return false;
    $message = '<ul>';
    foreach($_SESSION['msg'] as $msg){
      $message .= "<li>$msg</li>";
    }
    $message .= '</ul>';
    unset($_SESSION['msg']);
    return $message;
  }


  function dbQuery($query='')
  {
    global $debugArr;
    $result = mysql_query($query) or die(mysql_error());

    $traceArray = (array_reverse(debug_backtrace()));
    $file =$traceArray[0]['file'];
    $line = $traceArray[0]['line'];
    $debugArr[] = "$file on Line $line";
    pq($query);
    return $result;
  }

  function getForgotPasswordLink($id = 0)
  {
    global $site;
    global $linkExpireTime;
    $time = time()+ $linkExpireTime;
    $enc = encrypt($id.'#'.$time);
    return $link  = "<a href=\"$site/change_password.php?hash=$enc\">$site/change_password.php?hash=$enc</a>";
  }

 function encrypt($string='')
  {
    $string = trim($string);
    // This is 32 bit salt value change it
    $salt = '9iwjwj455aufj4669gafmdfkt244h45t';

    $encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256,
                                              md5($salt),
                                              $string,
                                              MCRYPT_MODE_CBC,
                                              md5(md5($salt))
                                             )
                              );
    return ($encrypted);
  }

  function decrypt($encrypted='')
  {
        $encrypted = trim($encrypted);

    // This is 32 bit salt value change it
    $salt = '9iwjwj455aufj4669gafmdfkt244h45t';

    $decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256,
                                      md5($salt),
                                      base64_decode($encrypted),
                                      MCRYPT_MODE_CBC,
                                      md5(md5($salt))
                                      ),
                  "\0");
    return ($decrypted);
  }

  function arrayCleanup($arr = array())
  {
    $arr  = array_map('strip_tags',$arr);
    $arr  = array_map('mysql_real_escape_string',$arr);
    $arr  = array_map('trim',$arr);
    return $arr;
  }

  function getStatus($status = 0)
  {
    return $status == 0 ? '<span title="Inactive" class="glyphicon glyphicon-star-empty"></span>' : '<span title="Active" class="glyphicon glyphicon-star"></span>';
  }


  function getGender($gender= 'm')
  {
    return $gender == 'f' ? 'Female' : 'Male';
  }


  /**
   * @param $name STRING Ixdex of $_FILES
   * ex : $_FILES['avatar']['size'] here $name is 'avatar'
   *
   * @param $uploadDir STRING Path where we have to upload file
   * @param $allowedExtn ARRAY
   * @param $allowedSize INT / FLOAT (SIZE in MB)
   * @return $msg = SUCCESS / FAIL
   * @return $uploadStatus BOOL true/ false
   * @return New File Name
   * **/

  function upload($name,$uploadDir = './uploads',
  $allowedExtn = array('jpg','jpeg','png'),
  $allowedSize = 1.0
  ){

    $uploadFlag = true;
    $fileName = '';
    if(is_uploaded_file($_FILES[$name]['tmp_name']))
    {
      $infoArr = pathinfo($_FILES[$name]['name']);
      $extn = $infoArr['extension'];
      if(!in_array($extn,$allowedExtn )) {
        $uploadFlag = false;
        $msg = 'Please upload file with valid extension';
      } else {
        $uploadSize = $allowedSize * 1024 * 1024;
        if($_FILES[$name]['size'] > $uploadSize) {
          $uploadFlag = false;
          $msg = "Please upload file with max $allowedSize MB";
        }
      }
    } else {// end if(is_uploaded_file)
      $uploadFlag = false;
      $msg = "Upload error!! Please try again later.<br>
      Please upload file with max $allowedSize MB.";
    }
    if($uploadFlag == false){
      pr1($msg);
    } else {
      $fileName = $_FILES[$name]['name'];
      $src =  $_FILES[$name]['tmp_name'];
      $fileName  = date('ymdHis').'_'.uniqid().'_'.$fileName;
      $dest = "$uploadDir/$fileName";
      move_uploaded_file($src, $dest);
      $msg = "File uploaded successfully";
    }
    return array(
    'flag' => $uploadFlag,
    'msg' => $msg,
    'fileName' => $fileName
    );
  }// end upload()


  function getCountries()
  {
    $country = array(
      1=>'India',
      2=>'China',
      3=>'Nepal',
      4=>'Bhutan'
    );
    return $country;
  }

  function getLanguages()
  {
    $lang = array(
      'c'=>'C',
      'cpp'=>'C++',
      'java'=>'Java',
      'dotnet'=>'.NET',
      'php'=>'PHP'
    );
    return $lang;
  }

  function getHobbies()
  {
    $hobbies = array(
      'ck'=>'Cricket',
      'hk'=>'Hockey',
      'fb'=>'Football',
      'ch'=>'Chess',
      'te'=>'Tennis'
    );
    return $hobbies;
  }


  /*******************************************
   * DB FUNCTIONS
   * ******************************************/
   /***
    * @param $tableName STRING e.g. $tableName='users'
    * @param $data ARRAY e.g $data=array('name'=>'rasmus')
    * $data must contain key as Columns Name and value as
    * it's value
    * @return ID INT Record inserted on ID
    * ****/
   function insert($tableName='',$data=array())
   {
     $query = "INSERT INTO `$tableName` SET ";
     foreach($data as $colName=>$val)
     {
        $query .= "`$colName`='$val' ,";
     }
     $query = rtrim($query,' ,');
     dbQuery($query);
     return mysql_insert_id();
   }

   /***
    * @param $tableName STRING e.g. $tableName='users'
    * @param $id INT e.g $id=5
    * @param $field STRING e.g $field="`name`,`email`,`phone`"
    * @return $array TUPLES
    * ****/
   function fetchById($tableName='',$id=0,$fields='*')
   {
     if($tableName==''){
       die('Please call <code>'. __FUNCTION__ . '()</code> with table name');
     }

      if($id != 0){
        $where = " WHERE `id`= '$id'";
      }
      if($fields == ''){
        $fields = "*";
      }
      $query = "SELECT $fields FROM `$tableName` $where";
      $result = dbQuery($query);
      return mysql_fetch_assoc($result);
   }

   /***
    * @param $tableName STRING e.g. $tableName='users'
    * @param $where STRING e.g $where="`name`='rasmus'"
    * @param $field STRING e.g $field="`name`,`email`,`phone`"
    * @param $where STRING e.g $order="`added_date DESC`"
    * @param $limit STRING e.g $limit="0,3"
    * @return $result RESOURCE
    * ****/
   function fetchAll($tableName='',$where='',$fields='*',$order='',$limit='')
   {
     if($tableName==''){
       die('Please call <code>'. __FUNCTION__ . '()</code> with table name');
     }

      if($where != ''){
        $where = " WHERE $where";
      }
      if($fields == ''){
        $fields = "*";
      }
      if($order != ''){
        $order = " ORDER BY $order";
      }
      if($limit != ''){
        $limit = " LIMIT $limit";
      }
      $query = "SELECT $fields FROM `$tableName` $where $order $limit";
//var_dump($query);exit;
      $result = dbQuery($query);
      return $result;
   }

    function fetchColNames($tableName='')
    {
      if($tableName==''){
       die('Please call <code>'. __FUNCTION__ . '()</code> with table name');
      }

      $query = "DESCRIBE `$tableName`";
      $result = dbQuery($query);
      $fields = array();

      while($ans = mysql_fetch_assoc($result))
      {
        $fields[] = $ans['Field'];
      }
      return $fields;

    }


   /***
    * Used to count total users
    * @param $tableName STRING e.g. $tableName='users'
    * @param $where STRING e.g $where="`name`='rasmus'"
    * @return INT $count
    * ****/
   function countAll($tableName='',$where='')
   {
     if($tableName==''){
       die('Please call <code>'. __FUNCTION__ . '()</code> with table name');
     }

      if($where != ''){
        $where = " WHERE $where";
      }
      $query = "SELECT COUNT(*) as `total` FROM `$tableName` $where";
      $result = dbQuery($query);
      $ans = mysql_fetch_assoc($result);

      return $ans['total'];
   }


   function deleteById($tableName='',$id = 0){
     if($tableName==''){
       die('Please call <code>'. __FUNCTION__ . '()</code> with table name');
     }
      $query = "DELETE FROM `$tableName` WHERE `id`='$id'";
      dbQuery($query) ;
      return mysql_affected_rows();
   }


   function updateById($tableName='',$id = 0,
   $data=array()){
     if($tableName==''){
       die('Please call <code>'. __FUNCTION__ . '()</code> with table name');
     }
      $query = "UPDATE `$tableName` SET ";
     foreach($data as $colName=>$val)
     {
        $query .= "`$colName`='$val' ,";
     }
     $query = rtrim($query,' ,');
     $query = "$query WHERE `id`='$id'";

      dbQuery($query);
      return mysql_affected_rows();
   }
